import React, { Children, Dispatch, SetStateAction } from 'react';
import { CollapseItemNameType, CollapseItemProps } from "./collapseItem";

export type CollapseValueType = Array<CollapseItemNameType> | CollapseItemNameType

export type CollapseSetValueType = Dispatch<SetStateAction<CollapseValueType>>

interface CollapseProps {
    value: CollapseValueType
    setValue: CollapseSetValueType
    className?: string
    style?: React.CSSProperties
    // 是否开启手风琴模式
    accordion?: boolean
    children: React.ReactNode
}

const Collapse: React.FC<CollapseProps> = props => {

    const { accordion, children, value, setValue } = props;

    const renderChildren = () => {
        if (accordion) {
            return Children.map(children, (child) => {
                const childElement = child as React.FunctionComponentElement<CollapseItemProps>
                if (childElement.type.displayName === 'CollapseItem') {
                    return React.cloneElement(childElement, { isOpen: value === childElement.props.name ? true : false, setValue, accordion, value });
                } else {
                    console.log('Warning: Collapse 组件的子组件只能是CollapseItem');
                }
            });
        } else {
            return Children.map(children, (child) => {
                const childElement = child as React.FunctionComponentElement<CollapseItemProps>
                if (childElement.type.displayName === 'CollapseItem' && value instanceof Array) {
                    return React.cloneElement(childElement, { isOpen: value.find((item) => item === childElement.props.name) ? true : false, setValue, accordion, value });
                } else {
                    console.log('Warning: Collapse 组件的子组件只能是CollapseItem');
                }

            });
        }
    }
    
    return <div className={"packages-yulang-collapse-container"}>{renderChildren()}</div>
}

Collapse.defaultProps = {
    accordion: false
}

export default Collapse;